var express = require("express");
var router = express.Router();
// var async = require("async");
const comment = require("../model/comment");
const comfabulous = require("../model/comfabulous");
router.post("/api/v1/getComment", async (req, res) => {
  // console.log(req.body);
  let articleid = req.body.query.articleid;
  let fistComment = comment.find({
    articleid: articleid
  }).populate({path: 'userid', populate: {path: 'department'}});

  if (req.body.skip) {
    fistComment.skip(req.body.skip)
  }
  if (req.body.limit) {
    fistComment.limit(req.body.limit)
  }
  let result = await fistComment.exec();

  for (let index = 0; index < result.length; index++) {
    let element = result[index];
    let secondComment = await comfabulous
      .find({
        commentid: element._id
      })
      .populate(["userid", "replyid"]);
    element._doc.secondComment = secondComment;
  }
  let countnum
  if (req.body.count) {
    countnum = await comment.find({
      articleid: articleid
    }).count();
  }
  res.json({
    code: 200,
    data: result,
    countnum: countnum
  });
});


router.post("/api/v1/delectFistComment", async (req, res) => {
  console.log(req.body);
  await comment.deleteOne(req.body.query)
  await comfabulous.deleteMany({
    commentid: req.body.query._id
  })
  res.json({
    code: 200,
    data: "succse"
  });
})

// 导出模块（在 app.js 中引入）
module.exports = router;